package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:ahang
 * @create:2022-09-06 19:39
 * @Description:
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1.loginvo获取出传过来的 手机号 和 验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2.校验参数
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(20001,"验证码或手机号不能为空");
        }
        // TODO 3. 验证码是否正常
        String code_redis = redisTemplate.opsForValue().get(phone);
        if(!code_redis.equals(code)){
            throw new YyghException(20001,"验证码有误");
        }

        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(loginVo.getOpenid())){
            //4.手机号是否存在
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(queryWrapper);
            //5.如果不存在则注册
            if(userInfo == null){
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
            //6.判断用户状态
            if(userInfo.getStatus().intValue() == 0){
                throw new YyghException(20001,"用户锁定,登陆失败");
            }
            //7.返回name 和 token

            map = this.get(userInfo);
        }else{
            String openid = loginVo.getOpenid();

            // 根据openid查询---》userInfo
            UserInfo userInfo_wx = this.selectWeixinByOpenid(openid);
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",loginVo.getPhone());

            UserInfo userInfo_phone = baseMapper.selectOne(queryWrapper);


            if(userInfo_phone!=null){
                //合并
                userInfo_wx.setPhone(userInfo_phone.getPhone());
                userInfo_wx.setName(userInfo_phone.getName());
                userInfo_wx.setCertificatesType(userInfo_phone.getCertificatesType());
                userInfo_wx.setCertificatesNo(userInfo_phone.getCertificatesNo());
                userInfo_wx.setCertificatesUrl(userInfo_phone.getCertificatesUrl());
                userInfo_wx.setAuthStatus(userInfo_phone.getAuthStatus());
                userInfo_wx.setStatus(userInfo_phone.getStatus());

//                baseMapper.deleteById(userInfo_phone.getId());//或者根据手机号去删除
                baseMapper.delete(new QueryWrapper<UserInfo>().eq("phone",loginVo.getPhone()));

                baseMapper.updateById(userInfo_wx);

            }else {
//                userInfo_phone     没有查询到
                userInfo_wx.setPhone(loginVo.getPhone());
                baseMapper.updateById(userInfo_wx);
            }
            map = this.get(userInfo_wx);
        }
        return map;
    }

    public Map get(UserInfo userInfo){
        Map<String,Object> map = new HashMap<>();
        String name = userInfo.getName();//用户的真实姓名（用户认证）
        if(StringUtils.isEmpty(name)){
            name = userInfo.getNickName();//微信昵称
            if(StringUtils.isEmpty(name)){
                name = userInfo.getPhone();
            }
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        map.put("name",name);
        return map;
    }

    //根据openid查询userinfo
    @Override
    public UserInfo selectWeixinByOpenid(String openid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;
    }

    //用户认证
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);

        String name = userAuthVo.getName();
        String certificatesType = userAuthVo.getCertificatesType();
        String certificatesNo = userAuthVo.getCertificatesNo();
        String certificatesUrl = userAuthVo.getCertificatesUrl();

        userInfo.setName(name);
        userInfo.setCertificatesType(certificatesType);
        userInfo.setCertificatesNo(certificatesNo);
        userInfo.setCertificatesUrl(certificatesUrl);

        //修改认证状态
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        baseMapper.updateById(userInfo);

    }
}
